﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using RBAC.API.Command.Role;
using System.Transactions;

namespace RBAC.API.Handler.Role
{
    public class RoleDelHandler:IRequestHandler<RoleDelCommand,ApiResult<int>>
    {
        private readonly IRepository<RoleModel> roleway;
        private readonly IRepository<RolePermissionModel> rolepermissionway;
        private readonly IRepository<PermissionModel> permissionway;
        private readonly IMapper mapper;
        private readonly ILogger<RoleGetHandler> log;
        private readonly IHttpContextAccessor httpContextAccessor;

        public RoleDelHandler(IRepository<RoleModel> roleway, IRepository<RolePermissionModel> rolepermissionway,
            IRepository<PermissionModel> permissionway, IMapper mapper, ILogger<RoleGetHandler> log, IHttpContextAccessor httpContextAccessor)
        {
            this.roleway = roleway;
            this.rolepermissionway = rolepermissionway;
            this.permissionway = permissionway;
            this.mapper = mapper;
            this.log = log;
            this.httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 角色删除
        /// </summary>
        /// <param name="request">角色主键</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        public async Task<ApiResult<int>> Handle(RoleDelCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            int i = 0;
            int l = 0;
            var role = await roleway.GetValue(request.Id);
            role.IsDel = true;
            var roles = rolepermissionway.GetAll().Where(x => x.RoleId == request.Id && x.IsDel == false).ToList();
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    i = await roleway.Updateway(role);
                    foreach (var item in roles)
                    {
                        item.IsDel = true;
                        l += await rolepermissionway.Updateway(item);
                    }
                    tran.Complete();  //提交
                }
                catch (Exception ex)
                {
                    log.LogInformation($"角色删除发生异常{ex.Message}");
                    //回滚
                    throw;
                }
            }
            if (i > 0 && l > 0)
            {
                log.LogInformation($"{DateTime.Now}{httpContextAccessor.HttpContext?.User.Claims?.FirstOrDefault(x => x.Type == "UserName")?.Value ?? "默认值"}");
                res.Code = StateCode.OK;
                res.Message = "角色删除成功";
                res.Data = i + l;
                return res;
            }
            else
            {
                res.Code = StateCode.Fail;
                res.Message = "角色删除失败";
                return res;
            }



        }
    }
    
}
